package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序工具组件接口实现类
 *
 * @Author Ls
 * @Date 2025/10/22 15:49
 */
@Service
public class WechatServiceImpl implements WechatService {

    // 获取openId的url
    private static final String GET_OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    // 获取手机号url
    private static final String GET_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    // 获取access_token的url
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    @Value("${wechat.appid}")
    String appid;

    @Value("${wechat.secret}")
    String secret;

    /**
     * 根据临时凭证码（openId获取专用凭证码）获取openId
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        Map<String,Object> paramMap = this.getCommonParamMap();
        paramMap.put("js_code",code);
        paramMap.put("grant_type","authorization_code");
        String result = HttpUtil.get(GET_OPEN_ID_URL, paramMap);

        if (StrUtil.isBlank( result)){
            throw new BaseException("获取openId失败");
        }
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return jsonObject.getStr("openid");
    }


    /**
     * 根据临时凭证码（手机号获取专用凭证码，非openId凭证码）获取手机号
     *
     * @param code
     * @return
     */
    @Override
    public String getPhone(String code) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("code",code);

        String result = HttpUtil.post(GET_PHONE_URL + this.getAccessToken(), JSONUtil.toJsonStr(paramMap));
        if (StrUtil.isBlank( result)){
            throw new BaseException("获取手机号失败");
        }
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String phoneInfo = jsonObject.getStr("phone_info");
        if (StrUtil.isNotBlank(phoneInfo)){
            JSONObject phoneObject = JSONUtil.parseObj(phoneInfo);
            return phoneObject.getStr("phoneNumber");
        }

        return null;
    }

    private String getAccessToken(){
        Map<String,Object> paramMap = this.getCommonParamMap();
        paramMap.put("grant_type","client_credential");

        String result = HttpUtil.get(GET_ACCESS_TOKEN_URL, paramMap);
        if (StrUtil.isBlank( result)){
            throw new BaseException("获取access_token失败");
        }
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return jsonObject.getStr("access_token");
    }


    private Map<String,Object> getCommonParamMap(){
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("appid",appid);
        paramMap.put("secret",secret);
        return paramMap;
    }
}
